package com.yonyou.brigade.third_parties.ctripBC.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannelAccount;
import com.yonyou.brigade.basic_init.service.IBriChannelAccountService;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.order_center.service.IBriOrderService;
import com.yonyou.brigade.third_parties.ctripBC.constants.CtripBCConstants;
import com.yonyou.brigade.third_parties.ctripBC.model.CtripBCConfig;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCOrderService;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCPublicService;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.framework.util.StringUtil;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;

/**
 * 携程（大客户）订单服务实现类
 *
 * @Auther: kangfw5
 * @Date: 2019/1/8 10:19
 */
@Service
public class CtripBCOrderServiceImpl implements ICtripBCOrderService {
    private static Logger logger = LoggerFactory.getLogger(CtripBCOrderServiceImpl.class);

    @Value("${smectrip.url}")
    private String URL;

    @Value("${ctripBC.tradeFlightType}")
    private String ctripBCFlightTradeType;

    @Value("${ctripBC.tradeTrainType}")
    private String ctripBCTrainTradeType;

    @Value("${ctripBC.tradeHotelType}")
    private String ctripBCHotelTradeType;

    @Value("${ctripBC.tradeCarType}")
    private String ctripBCCarTradeType;

    @Value("${ctripBC.tradeCarQuickType}")
    private String ctripBCCarQuickTradeType;

    @Value("${ctripBC.tradeDomPickUpType}")
    private String ctripBCDomPickUpTradeType;

    @Value("${ctripBC.tradeDomCharterCarType}")
    private String ctripBCDomCharterCarTradeType;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.register.userId}")
    private String cnvRegisterUserId;

    @Value("${cnv.register.tenant}")
    private String cnvRegisterTenant;

    @Value("${cnv.register.cookie}")
    private String cnvRegisterCookie;

    @Autowired
    @Qualifier("ctripBCPublicServiceImpl")
    private ICtripBCPublicService ctripBCPublicService;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService convertService;

    @Autowired
    @Qualifier("briChannelAccountServiceImpl")
    private IBriChannelAccountService briChannelAccountService;

    @Autowired
    @Qualifier("briOrderServiceImpl")
    private IBriOrderService briOrderService;

    @Autowired
    private IMongoDao mongoDao;

    // 根据订单号查询携程数据事的最大订单数 防止查询超时
    private final static int maxQueryNum = 30;

    @Value("${ctripBC.tradeSettleFlightType}")
    private String ctripBCTradeSettleFlightType;

    @Value("${ctripBC.tradeSettleHotelType}")
    private String ctripBCTradeSettleHotelType;

    @Value("${ctripBC.tradeSettleTrainType}")
    private String ctripBCTradeSettleTrainType;

    @Value("${ctripBC.tradeSettleCarType}")
    private String ctripBCTradeSettleCarType;

    /**
     * 携程（大客户）订单拉取及保存到订单中心
     *
     * @Auther: kangfw5
     * @Date: 2019/1/8 10:19
     */
    @Override
    public void getCtripBCOrders(String tenant, String orgPk, String beginDate, String endDate, int channelId, CtripBCConfig config) {
        //CtripBCConfig channelConfig = (CtripBCConfig) briChannelService.getChannelConfig(tenant, ChannelEnum.CTRIPBC.getName(), orgPk, new CtripBCConfig());
        String orderResultString = ctripBCPublicService.doRMIOrdersSearch(beginDate, endDate, config);
        if (StringUtils.isNotEmpty(orderResultString)) {
            JSONObject orderJSONObject = JSONObject.parseObject(orderResultString);
            JSONObject statusJSONObject = orderJSONObject.getJSONObject("Status");
            if (statusJSONObject == null || !statusJSONObject.getBoolean("Success")) {
                logger.error("携程（大客户）拉单请求失败，请求参数[tenant,orgPk,beginDate,endDate,channelId]:[" + tenant + "," + orgPk + "," + beginDate + ","
                        + endDate + "," + channelId + "],请求结果：" + orderResultString);
            } else {
                JSONArray itineraryList = orderJSONObject.getJSONArray("ItineraryList");
                if (itineraryList != null && itineraryList.size() > 0) {
                    for (int i = 0; i < itineraryList.size(); i++) {
                        JSONObject itineraryJSONObject = itineraryList.getJSONObject(i);
                        // 订单转换与保存
                        doConvertAndSave(itineraryJSONObject, tenant, channelId);
                    }
                }
            }
        }
    }

    /**
     * @param searchType    产品类别 1：机票、酒店、火车票、用车、马上用车 2：机票 3：火车票 4：酒店 5：用车（包含老版国内接送机、国际接送机、国内租车） 6：马上用车 7：新版国内接送机 8：国内包车
     * @param orderIdList   订单号
     * @param tenant        租户ID
     * @param channelId     渠道ID
     * @param ctripBCConfig 携程配置信息
     * @description: 按照订单号和产品类别拉取并保存或更新订单
     * @since 2019-02-26
     */
    @Override
    public void getCtripBCOrdersByOrderId(String searchType, List<String> orderIdList, String tenant, int channelId, CtripBCConfig ctripBCConfig) {
        // 每次最多查询30条避免超时
        int updateLength = orderIdList.size();
        int m = 0;
        while (updateLength > maxQueryNum) {
            String orderIds = String.join(",", orderIdList.subList(m, m + maxQueryNum));
            getOrUpdateOrdersById(searchType, orderIds, tenant, channelId, ctripBCConfig);
            m = m + maxQueryNum;
            updateLength = updateLength - maxQueryNum;
        }
        if (updateLength > 0) {
            String orderIds = String.join(",", orderIdList.subList(m, m + updateLength));
            getOrUpdateOrdersById(searchType, orderIds, tenant, channelId, ctripBCConfig);
        }
    }

    /**
     * 机票订单结算明细
     * @param tenant
     * @param orgPk
     * @param beginDate
     * @param endDate
     * @param channelId
     * @param config
     */
    @Override
    public void getCtripBCFlightSettleOrders(String tenant, String orgPk, String beginDate, String endDate, int channelId, CtripBCConfig config) {
        String flightOrderResultString = ctripBCPublicService.SearchSettlementFlightOrder(beginDate, endDate, config);
        if (StringUtils.isNotEmpty(flightOrderResultString)) {
            JSONObject orderJSONObject = JSONObject.parseObject(flightOrderResultString);
            JSONObject statusJSONObject = orderJSONObject.getJSONObject("Status");
            if (statusJSONObject == null || !statusJSONObject.getBoolean("Success")) {
                logger.error("携程（大客户机票结算明细请求失败，请求参数[tenant,orgPk,beginDate,endDate,channelId]:[" + tenant + "," + orgPk + "," + beginDate + ","
                        + endDate + "," + channelId + "],请求结果：" + flightOrderResultString);
            } else {
                JSONArray flightOrderAccountSettlementList = orderJSONObject.getJSONArray("FlightOrderAccountSettlementList");
                if (flightOrderAccountSettlementList != null && flightOrderAccountSettlementList.size() > 0) {
                    for (int i = 0; i < flightOrderAccountSettlementList.size(); i++) {
                        JSONObject flightOrderAccountSettlementInfo = flightOrderAccountSettlementList.getJSONObject(i);
                        // 订单转换与保存
                        doSettleOrderConvertAndSave(flightOrderAccountSettlementInfo, tenant, channelId);
                    }
                }
            }
        }
    }

    /**
     * 酒店订单结算明细
     * @param tenant
     * @param orgPk
     * @param beginDate
     * @param endDate
     * @param channelId
     * @param config
     */
    @Override
    public void getCtripBCHotelSettleOrders(String tenant, String orgPk, String beginDate, String endDate, int channelId, CtripBCConfig config) {
        String hotellOrderResultString = ctripBCPublicService.SearchSettlementHtlOrder(beginDate, endDate, config);
        if (StringUtils.isNotEmpty(hotellOrderResultString)) {
            JSONObject orderJSONObject = JSONObject.parseObject(hotellOrderResultString);
            JSONObject statusJSONObject = orderJSONObject.getJSONObject("Status");
            if (statusJSONObject == null || !statusJSONObject.getBoolean("Success")) {
                logger.error("携程（大客户）酒店结算明细请求失败，请求参数[tenant,orgPk,beginDate,endDate,channelId]:[" + tenant + "," + orgPk + "," + beginDate + ","
                        + endDate + "," + channelId + "],请求结果：" + hotellOrderResultString);
            } else {
                JSONArray HtlSettlementList = orderJSONObject.getJSONArray("LstHtlSettlement");
                if (HtlSettlementList != null && HtlSettlementList.size() > 0) {
                    for (int i = 0; i < HtlSettlementList.size(); i++) {
                        JSONObject hotelOrderSettlementInfo = HtlSettlementList.getJSONObject(i);
                        // 订单转换与保存
                        doSettleOrderConvertAndSave(hotelOrderSettlementInfo, tenant, channelId);
                    }
                }
            }
        }
    }

    /**
     * 火车订单结算明细
     * @param tenant
     * @param orgPk
     * @param beginDate
     * @param endDate
     * @param channelId
     * @param config
     */
    @Override
    public void getCtripBCTrainSettleOrders(String tenant, String orgPk, String beginDate, String endDate, int channelId, CtripBCConfig config) {
        String trainOrderResultString = ctripBCPublicService.SearchSettlementTrainOrder(beginDate, endDate, config);
        if (StringUtils.isNotEmpty(trainOrderResultString)) {
            JSONObject orderJSONObject = JSONObject.parseObject(trainOrderResultString);
            JSONObject statusJSONObject = orderJSONObject.getJSONObject("Status");
            if (statusJSONObject == null || !statusJSONObject.getBoolean("Success")) {
                logger.error("携程（大客户）火车票结算明细请求失败，请求参数[tenant,orgPk,beginDate,endDate,channelId]:[" + tenant + "," + orgPk + "," + beginDate + ","
                        + endDate + "," + channelId + "],请求结果：" + trainOrderResultString);
            } else {
                JSONArray trainOrderSettlementList = orderJSONObject.getJSONArray("LstTrainSettlement");
                if (trainOrderSettlementList != null && trainOrderSettlementList.size() > 0) {
                    for (int i = 0; i < trainOrderSettlementList.size(); i++) {
                        JSONObject trainOrderSettlementInfo = trainOrderSettlementList.getJSONObject(i);
                        // 订单转换与保存
                        doSettleOrderConvertAndSave(trainOrderSettlementInfo, tenant, channelId);
                    }
                }
            }
        }
    }

    /**
     * 用车订单结算明细
     * @param tenant
     * @param orgPk
     * @param beginDate
     * @param endDate
     * @param channelId
     * @param config
     */
    @Override
    public void getCtripBCCarSettleOrders(String tenant, String orgPk, String beginDate, String endDate, int channelId,CtripBCConfig config) {
        String carOrderResultString = ctripBCPublicService.SearchSettlementCarOrder(beginDate, endDate, config);
        if (StringUtils.isNotEmpty(carOrderResultString)) {
            JSONObject orderJSONObject = JSONObject.parseObject(carOrderResultString);
            JSONObject statusJSONObject = orderJSONObject.getJSONObject("Status");
            if (statusJSONObject == null || !statusJSONObject.getBoolean("Success")) {
                logger.error("携程（大客户）用车结算明细请求失败，请求参数[tenant,orgPk,beginDate,endDate,channelId]:[" + tenant + "," + orgPk + "," + beginDate + ","
                        + endDate + "," + channelId + "],请求结果：" + carOrderResultString);
            } else {
                JSONArray carOrderSettlementList = orderJSONObject.getJSONArray("CarOrderAccountSettlementList");
                if (carOrderSettlementList != null && carOrderSettlementList.size() > 0) {
                    for (int i = 0; i < carOrderSettlementList.size(); i++) {
                        JSONObject carOrderSettlementInfo = carOrderSettlementList.getJSONObject(i);
                        // 订单转换与保存
                        doSettleOrderConvertAndSave(carOrderSettlementInfo, tenant, channelId);
                    }
                }
            }
        }
    }

    /**
     * 解析订单 沿用之前的代码
     *
     * @param OrderSettlementJson
     */
    private void doSettleOrderConvertAndSave(JSONObject OrderSettlementJson, String tenant, int channelId) {
        JSONObject res;
        //机票结算数据处理
        JSONArray orderSettlementList = OrderSettlementJson.getJSONArray("OrderSettlementList");
        if (null != orderSettlementList) {
            for (int i = 0; i < orderSettlementList.size(); i++) {
                JSONObject flightOrder = orderSettlementList.getJSONObject(i);
                JSONObject orderSettlementBaseInfo = flightOrder.getJSONObject("OrderSettlementBaseInfo");
                if (StringUtil.isEmpty(orderSettlementBaseInfo.getString("OrderID"))) {
                    logger.error("携程机票RecordID为" + orderSettlementBaseInfo.getString("RecordID") + "结算数据订单号为空");
                    continue;
                }
                String orderNo = orderSettlementBaseInfo.getString("OrderID") + "_" + orderSettlementBaseInfo.getString("RecordID");
                flightOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                dealWithMongo("flight", orderNo, CtripBCConstants.FLIGHT_MONGO_ORDER_TABLENAME, flightOrder);
                res = convertService.convert(ctripBCTradeSettleFlightType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, flightOrder);
                // 根据主账号查询对应租户
                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(orderSettlementBaseInfo.getString("AccountID"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }
                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveFlight(orderCenter, orderNo, tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (ParseException e) {
                                    logger.error("保存携程(大客户)机票结算数据时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //酒店结算数据处理
        JSONArray hotelOrderInfoArr = OrderSettlementJson.getJSONArray("LstHotelSettlementDetail");
        if (null != hotelOrderInfoArr) {
            for (int i = 0; i < hotelOrderInfoArr.size(); i++) {
                JSONObject hotelOrderSettlementInfo = hotelOrderInfoArr.getJSONObject(i);
                if (StringUtil.isEmpty(hotelOrderSettlementInfo.getJSONObject("SettlementDetail").getString("OrderID"))) {
                    logger.error("携程酒店RecordID为" + hotelOrderSettlementInfo.getJSONObject("SettlementDetail").getString("RecordID") + "结算数据订单号为空");
                    continue;
                }
                String orderNo = hotelOrderSettlementInfo.getJSONObject("SettlementDetail").getString("OrderID") + "_" + hotelOrderSettlementInfo.getJSONObject("SettlementDetail").getString("RecordId");
                hotelOrderSettlementInfo.put("fromSource", ChannelEnum.CTRIPBC.getName());
                logger.info("ctripbc before convert:"+hotelOrderSettlementInfo.toJSONString());
                dealWithMongo("hotel", orderNo, CtripBCConstants.HOTEL_MONGO_ORDER_TABLENAME, hotelOrderSettlementInfo);
                res = convertService.convert(ctripBCTradeSettleHotelType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, hotelOrderSettlementInfo);
                logger.info("ctripbc after convert:"+res);
                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(hotelOrderSettlementInfo.getJSONObject("SettlementDetail").getString("AccountId"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }
                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveHotel(orderCenter, orderNo, tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (ParseException e) {
                                    logger.error("保存携程(大客户)酒店结算数据时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //火车结算数据处理
        JSONArray trainOrderInfoArr = OrderSettlementJson.getJSONArray("LstTrainSettlementDetail");
        if (null != trainOrderInfoArr) {
            for (int i = 0; i < trainOrderInfoArr.size(); i++) {
                JSONObject trainOrder = trainOrderInfoArr.getJSONObject(i);
                if (StringUtil.isEmpty(trainOrder.getJSONObject("TrainSettlementDetail").getString("OrderID"))) {
                    logger.error("携程火车票RecordID为" + trainOrder.getJSONObject("TrainSettlementDetail").getString("RecordID") + "结算数据订单号为空");
                    continue;
                }
                String orderNo = trainOrder.getJSONObject("TrainSettlementDetail").getString("OrderID") + "_" + trainOrder.getJSONObject("TrainSettlementDetail").getString("RecordID");
                trainOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                dealWithMongo("train", orderNo, CtripBCConstants.TRAIN_MONGO_ORDER_TABLENAME, trainOrder);
                res = convertService.convert(ctripBCTradeSettleTrainType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, trainOrder);
                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(trainOrder.getJSONObject("TrainSettlementDetail").getString("AccountID"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }
                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveTrain(orderCenter, orderNo, tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (Exception e) {
                                    logger.error("保存携程(大客户)火车票结算数据时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //用车结算数据处理
        JSONArray carSettlementDetailArr = OrderSettlementJson.getJSONArray("CarSettlementDetailList");
        if (null != OrderSettlementJson) {
            if (null != carSettlementDetailArr) {
                for (int n = 0; n < carSettlementDetailArr.size(); n++) {
                    JSONObject carOrderSettlementDetail = carSettlementDetailArr.getJSONObject(n);
                    if (StringUtil.isEmpty(carOrderSettlementDetail.getJSONObject("SettlementBaseInfo").getString("OrderID"))) {
                        logger.error("携程用车RecordID为" + carOrderSettlementDetail.getJSONObject("SettlementBaseInfo").getString("RecordId") + "结算数据订单号为空");
                        continue;
                    }
                    String orderNo = carOrderSettlementDetail.getJSONObject("SettlementBaseInfo").getString("OrderID") + "_" + carOrderSettlementDetail.getJSONObject("SettlementBaseInfo").getString("RecordId");
                    carOrderSettlementDetail.put("fromSource", ChannelEnum.CTRIPBC.getName());
                    dealWithMongo("car", orderNo, CtripBCConstants.CAR_MONGO_ORDER_TABLENAME, carOrderSettlementDetail);
                    res = convertService.convert(ctripBCTradeSettleCarType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, carOrderSettlementDetail);
                    BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(OrderSettlementJson.getString("AccountId"));
                    if (briChannelAccount == null) {
                        continue;
                    } else {
                        tenant = briChannelAccount.getTenant();
                    }
                    if (res.getBoolean("success")) {
                        JSONArray results = res.getJSONArray("result");
                        if (results != null && results.size() > 0) {
                            for (int j = 0; j < results.size(); j++) {
                                JSONObject jsonObject = results.getJSONObject(j);
                                JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                                if (orderCenter != null) {
                                    try {
                                        briOrderService.saveCar(orderCenter, orderNo, tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                    } catch (Exception e) {
                                        logger.error("保存携程(大客户)用车结算数据时出现错误：channelId：" + channelId, e);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }



    private void getOrUpdateOrdersById(String searchType, String orderIds, String tenant, int channelId, CtripBCConfig ctripBCConfig) {
        String orderResultString = ctripBCPublicService.doOrdersSearch(searchType, orderIds, ctripBCConfig);

        if (StringUtils.isNotEmpty(orderResultString)) {
            JSONObject orderResultJSON = JSONObject.parseObject(orderResultString);
            JSONObject statusJSONObject = orderResultJSON.getJSONObject("Status");
            if (statusJSONObject == null || !statusJSONObject.getBoolean("Success")) {
                logger.error("携程（大客户）按订单号拉取订单失败[tenant{},searchType{},orderIds{}]", tenant, searchType, orderIds);
            } else {
                JSONArray itineraryList = orderResultJSON.getJSONArray("ItineraryList");
                if (itineraryList != null && itineraryList.size() > 0) {
                    for (int i = 0; i < itineraryList.size(); i++) {
                        JSONObject itineraryJSONObject = itineraryList.getJSONObject(i);
                        // 订单转换与保存
                        doConvertAndSave(itineraryJSONObject, tenant, channelId);
                    }
                }
            }
        }
    }

    /**
     * 解析订单 沿用之前的代码
     *
     * @param itineraryJson
     */
    private void doConvertAndSave(JSONObject itineraryJson, String tenant, int channelId) {
        JSONObject res;

        //酒店订单处理
        JSONArray hotelOrderInfoArr = itineraryJson.getJSONArray("HotelOrderInfoList");
        if (null != hotelOrderInfoArr) {
            for (int i = 0; i < hotelOrderInfoArr.size(); i++) {
                JSONObject hotelOrder = hotelOrderInfoArr.getJSONObject(i);
                String orderStatus = hotelOrder.getString("OrderStatus");
                if ("未提交".equals(orderStatus) || "已取消".equals(orderStatus)) {
                    continue;
                }
                hotelOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                dealWithMongo("hotel", hotelOrder.getString("OrderID"), CtripBCConstants.HOTEL_MONGO_ORDER_TABLENAME, hotelOrder);
                res = convertService.convert(ctripBCHotelTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, hotelOrder);

                // 根据主账号查询对应租户
                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(hotelOrder.getString("FundAccount"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }

                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {

                                try {
                                    briOrderService.saveHotel(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (ParseException e) {
                                    logger.error("保存携程(大客户)酒店订单时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //飞机订单处理
        JSONArray flightOrderInfoArr = itineraryJson.getJSONArray("FlightOrderInfoList");
        if (null != flightOrderInfoArr) {
            for (int i = 0; i < flightOrderInfoArr.size(); i++) {
                JSONObject flightOrder = flightOrderInfoArr.getJSONObject(i);
                flightOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                logger.info("ctripbc before convert:"+flightOrder.toJSONString());
                dealWithMongo("flight", flightOrder.getJSONObject("BasicInfo").getString("OrderID"), CtripBCConstants.FLIGHT_MONGO_ORDER_TABLENAME, flightOrder);
                res = convertService.convert(ctripBCFlightTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, flightOrder);
                logger.info("ctripbc after convert:"+res);

                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(flightOrder.getJSONObject("BasicInfo").getString("AccountID"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }

                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveFlight(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (ParseException e) {
                                    logger.error("保存携程(大客户)机票订单时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //火车订单处理
        JSONArray trainOrderInfoArr = itineraryJson.getJSONArray("TrainOrderInfoList");
        if (null != trainOrderInfoArr) {
            for (int i = 0; i < trainOrderInfoArr.size(); i++) {
                JSONObject trainOrder = trainOrderInfoArr.getJSONObject(i);
                trainOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                dealWithMongo("train", trainOrder.getJSONObject("BasicInfo").getString("OrderID"), CtripBCConstants.TRAIN_MONGO_ORDER_TABLENAME, trainOrder);
                res = convertService.convert(ctripBCTrainTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, trainOrder);

                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(trainOrder.getJSONObject("CorpOrderInfo").getString("AccountID"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }

                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveTrain(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (Exception e) {
                                    logger.error("保存携程(大客户)火车票订单时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //用车信息处理
        JSONArray carOrderInfoArr = itineraryJson.getJSONArray("CarOrderInfoList");
        if (null != carOrderInfoArr) {
            for (int i = 0; i < carOrderInfoArr.size(); i++) {
                JSONObject carOrder= carOrderInfoArr.getJSONObject(i);
                carOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                dealWithMongo("car", carOrder.getJSONObject("BasicInfo").getString("OrderID"), CtripBCConstants.CAR_MONGO_ORDER_TABLENAME, carOrder);
                res = convertService.convert(ctripBCCarTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, carOrder);
                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(carOrder.getJSONObject("CorpOrderInfo").getString("AccountID"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }

                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveCar(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (Exception e) {
                                    logger.error("保存携程(大客户)用车信息订单时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //马上用车信息处理
        JSONArray carQuickOrderInfoArr = itineraryJson.getJSONArray("CarQuickOrderInfoList");
        if (null != carQuickOrderInfoArr) {
            for (int i = 0; i < carQuickOrderInfoArr.size(); i++) {
                JSONObject carQuickOrder= carQuickOrderInfoArr.getJSONObject(i);
                carQuickOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                dealWithMongo("carQuick", carQuickOrder.getJSONObject("BasicInfo").getString("OrderId"), CtripBCConstants.CARQUICK_MONGO_ORDER_TABLENAME, carQuickOrder);
                res = convertService.convert(ctripBCCarQuickTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, carQuickOrder);
                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(carQuickOrder.getJSONObject("BasicInfo").getString("AccountId"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }

                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveCar(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (Exception e) {
                                    logger.error("保存携程(大客户)马上用车信息订单时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //新版国内接送机信息处理
        JSONArray domPickUpOrderInfoArr = itineraryJson.getJSONArray("DomPickUpOrderInfoList");
        if (null != domPickUpOrderInfoArr) {
            for (int i = 0; i < domPickUpOrderInfoArr.size(); i++) {
                JSONObject domPickUpOrder= domPickUpOrderInfoArr.getJSONObject(i);
                domPickUpOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                dealWithMongo("domPickUp", domPickUpOrder.getJSONObject("DomPickUpCarBasicInfo").getString("OrderId"), CtripBCConstants.DOMPICKUP_MONGO_ORDER_TABLENAME, domPickUpOrder);
                res = convertService.convert(ctripBCDomPickUpTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, domPickUpOrder);
                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(domPickUpOrder.getJSONObject("DomPickUpCarBasicInfo").getString("AccountId"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }

                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveCar(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (Exception e) {
                                    logger.error("保存携程(大客户)新版国内接送机信息订单时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //国内包车信息处理
        JSONArray domCharterCarOrderInfoArr = itineraryJson.getJSONArray("DomCharterCarOrderInfoList");
        if (null != domCharterCarOrderInfoArr) {
            for (int i = 0; i < domCharterCarOrderInfoArr.size(); i++) {
                JSONObject domCharterCarOrder = domCharterCarOrderInfoArr.getJSONObject(i);
                domCharterCarOrder.put("fromSource", ChannelEnum.CTRIPBC.getName());
                dealWithMongo("domCharter", domCharterCarOrder.getJSONObject("DomCharterCarBasicInfo").getString("OrderId"), CtripBCConstants.DOMCHARTER_MONGO_ORDER_TABLENAME, domCharterCarOrder);
                res = convertService.convert(ctripBCDomCharterCarTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, domCharterCarOrder);
                BriChannelAccount briChannelAccount = briChannelAccountService.getEnableChannelAccountByAccount(domCharterCarOrder.getJSONObject("DomCharterCarBasicInfo").getString("AccountId"));
                if (briChannelAccount == null) {
                    continue;
                } else {
                    tenant = briChannelAccount.getTenant();
                }

                if (res.getBoolean("success")) {
                    JSONArray results = res.getJSONArray("result");
                    if (results != null && results.size() > 0) {
                        for (int j = 0; j < results.size(); j++) {
                            JSONObject jsonObject = results.getJSONObject(j);
                            JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                            if (orderCenter != null) {
                                try {
                                    briOrderService.saveCar(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.CTRIPBC.getName(), channelId);
                                } catch (Exception e) {
                                    logger.error("保存携程(大客户)国内包车信息订单时出现错误：channelId：" + channelId, e);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void dealWithMongo(String type, String orderId, String mongoName, JSONObject orderJson) {
        CriteriaMap criteriaMap = new CriteriaMap();
        if ("hotel".equals(type)) {
            criteriaMap.put("OrderID",orderId);
        } else if ("flight".equals(type) || "train".equals(type) || "car".equals(type)) {
            criteriaMap.put("BasicInfo.OrderID",orderId);
        } else if ("carQuick".equals(type)) {
            criteriaMap.put("BasicInfo.OrderId",orderId);
        } else if ("domPickUp".equals(type)) {
            criteriaMap.put("DomPickUpCarBasicInfo.OrderId",orderId);
        } else if ("domCharter".equals(type)) {
            criteriaMap.put("DomCharterCarBasicInfo.OrderId",orderId);
        }
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, mongoName);
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, mongoName);
            mongoDao.getMongoTemplate().save(orderJson, mongoName);
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson, mongoName);
        }
    }


    private void dealSettleOrderWithMongo(String type, Long orderId, String mongoName, JSONObject orderJson) {
        CriteriaMap criteriaMap = new CriteriaMap();
        if ("hotel".equals(type)) {
            criteriaMap.put("OrderID",orderId);
        } else if ("flight".equals(type) || "train".equals(type) || "car".equals(type)) {
            criteriaMap.put("BasicInfo.OrderID",orderId);
        } else if ("carQuick".equals(type)) {
            criteriaMap.put("BasicInfo.OrderId",orderId);
        } else if ("domPickUp".equals(type)) {
            criteriaMap.put("DomPickUpCarBasicInfo.OrderId",orderId);
        } else if ("domCharter".equals(type)) {
            criteriaMap.put("DomCharterCarBasicInfo.OrderId",orderId);
        }
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, mongoName);
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, mongoName);
            mongoDao.getMongoTemplate().save(orderJson, mongoName);
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson, mongoName);
        }
    }
}
